// useAudioPlayer.js
import { ref, watch } from "vue"

export function useAudioPlayer(initialUrl) {
  const audioContext = ref(null)
  const currentUrl = ref(initialUrl)

  const initAudio = (url) => {
    if (audioContext.value) {
      audioContext.value.destroy()
    }

    audioContext.value = uni.createInnerAudioContext()
    audioContext.value.src = url
  }

  const playAudio = () => {
    if (audioContext.value) {
      audioContext.value.play()
    }
  }

  const pauseAudio = () => {
    if (audioContext.value) {
      audioContext.value.pause()
    }
  }

  const stopAudio = () => {
    if (audioContext.value) {
      audioContext.value.stop()
    }
  }

  const destroyAudio = () => {
    if (audioContext.value) {
      audioContext.value.destroy()
      audioContext.value = null
    }
  }

  watch(currentUrl, (newUrl) => {
    initAudio(newUrl)
  })

  initAudio(initialUrl)

  return {
    currentUrl,
    playAudio,
    pauseAudio,
    stopAudio,
    destroyAudio,
  }
}
